//国际合作
<template>
  <div class="module_">
    <div class="mb8">
      <search @clearSearch='clearSearch' :status='true'>
        <el-form label-width='95px' inline autocomplete="off" :model="pageparm" class="search_box">
          <el-form-item label="合同名称">
            <el-input size="medium" clearable v-model="pageparm.name" placeholder="请输入合同名称搜索" />
          </el-form-item>
          <el-form-item label="负责人姓名">
            <inputSearch ref="search_e" placeholder="请输入负责人姓名搜索" @onChange='searchChane($event,"leader_id")' />
          </el-form-item>
          <el-form-item label="负责人类型">
            <el-select size="medium" v-model="pageparm.leader_type" clearable
              @change='searchChane($event,"leader_type")' placeholder="请选择负责人类型">
              <el-option v-for="item in leaderType" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="科室" v-if="adminShow">
            <inputSearch ref="search_d" type='departments' @onChange='searchChane($event,"departments_id")' />
          </el-form-item>
          <el-form-item label="开始日期">
            <el-date-picker v-model="pageparm.start_time" type="daterange" range-separator="至" start-placeholder="日期范围"
              end-placeholder="日期范围" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
              @change="searchChane($event,'start_time')">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="终止日期">
            <el-date-picker v-model="pageparm.end_time" type="daterange" range-separator="至" start-placeholder="日期范围"
              end-placeholder="日期范围" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
              @change="searchChane($event,'end_time')">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select size="medium" clearable v-model="pageparm.review_status" placeholder="请选择审核状态搜索"
              @change='searchChane($event,"review_status")'>
              <el-option v-for="item in reviewStatus" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template slot="footer">
          <el-button v-permission="{action:'国际合作添加',effect:'delete'}" class="mr8" size="medium" type="primary"
            @click="handle(null,{},3)">新增国际合作</el-button>
          <exportExcel :apiFn='ApiInternationalcontracts' :self='true' :dataFn='dataFn' name='国际合作' />
        </template>
      </search>
    </div>
    <el-table :data="tableData" class="flex-1" height="100%" size="medium" border highlight-current-row
      v-loading="tableLoading" stripe @sort-change="tableSortChange" @row-click='viewDetails'>
      <el-table-column align="center" v-for="(item,i) in headerList" :key="item.prop" :prop="item.prop"
        :label="item.label + (item.unit || '')" :width="item.width" :fixed="i === 0 ? true: false" show-overflow-tooltip
        :sortable="item.noSort?false:'custom'">
        <template slot-scope="scope">
          <template v-if="item.prop === 'departments_id'">
            {{ scope.row.department?scope.row.department.name:'' }}
          </template>
          <template v-else-if="item.prop === 'leader_id'">
            {{ scope.row.leader_info?scope.row.leader_info.name:''}}
          </template>
          <template v-else-if="item.prop === 'complete_id'">
            {{objToStr(scope.row.complete_name)}}
          </template>
          <template v-else-if="item.prop === 'review_status'">
            <span v-if="scope.row.review_comment" class="c-red">{{scope.row.status}}：{{scope.row.review_comment}}</span>
            <span v-else>{{scope.row.status}}</span>
          </template>
          <template v-else-if="item.prop === 'leader_type'">
            {{ echo(scope.row.leader_type,leaderType) }}
          </template>
          <template v-else>
            {{ scope.row[item.prop] }}
          </template>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" width="200" class-name="operation">
        <div class="flex-justify-end" slot-scope="scope">
          <el-tooltip effect="dark" content="审核" placement="bottom-end" v-show="scope.row.review_status == 0">
            <el-button v-permission="{action:'国际合作审核',effect:'delete'}" type="primary"
              @click.stop="examine_btns(scope.row,1)" size="small" icon="el-icon-help" circle></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="上传验收报告" placement="bottom-end" v-if="scope.row.accept">
            <el-button type="success" @click.stop="yanShou(scope.row)" size="small" icon="el-icon-s-promotion" circle>
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="修改信息" placement="bottom-end">
            <el-button v-permission="{action:'国际合作编辑',effect:'delete'}" size="small"
              @click.stop="handle(scope.$index, scope.row,2)" icon="el-icon-edit" circle></el-button>
          </el-tooltip>
          <!-- v-permission="{action:'国际合作删除',effect:'delete'}" -->
          <el-tooltip effect="dark" content="删除" placement="bottom-end">
            <el-button v-if="scope.row.delete" size="small" type="danger"
              @click.stop="deleteUser(scope.$index, scope.row)" icon="el-icon-delete" circle></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="添加项目成员" placement="bottom-end">
            <el-button v-if="scope.row.add_member" size="small" type="primary" @click.stop="goUserInfo(scope.row)"
              icon="el-icon-user" circle></el-button>
          </el-tooltip>
        </div>
      </el-table-column>
    </el-table>

    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>

    <el-dialog :visible.sync="editFormVisible" width="750px" @close='dialogClose'
      :close-on-click-modal='false' :close-on-press-escape='false' top="10vh">
      <h2 slot="title" class="tx-c">{{dialogTitle}}</h2>
      <el-form autocomplete="off" label-width="125px" :model="editForm" class="form_flex">
        <el-form-item v-for="(v, i) in editHeaderList" :key="i" :label="v.label" :class="v.required ? 'tip' : ''">
          <inputSearch :options="{type:'leader'}" v-if="v.prop === 'leader_id'" ref="e_Search" @onChange='nameChange'
            :middleList='middleList' />
          <inputSearch v-else-if="v.prop === 'departments_id'" ref="departmentSearch" type="departments"
            @onChange='departmentsChange' :departmentsId='departmentsId' />
          <multipleSearch :options="{type:'all'}" v-else-if="v.prop === 'complete_id'" ref="e2_Search" @onChange='completionChange'
            :middleList='personList' :middleInfoList="middleInfoList" />
          <el-select size="medium" v-else-if="v.prop === 'leader_type'" v-model="editForm[v.prop]" clearable
            placeholder="请选择负责人类型">
            <el-option v-for="item in leaderType" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <el-date-picker v-else-if="v.prop === 'start_time' || v.prop === 'end_time'" size="medium"
            v-model="editForm[v.prop]" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="选择日期时间"
            :picker-options='pickerOptions[v.prop]' @change="changeDate($event,v.prop)">
          </el-date-picker>
          <el-input v-else size="medium" :type="v.type" autosize clearable v-model="editForm[v.prop]"
            @mousewheel.native.prevent
            :placeholder="'请输入' + v.label">
            <template v-if="unitShow(v.prop)" slot="append">万元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="附件上传">
          <el-upload style="width: 500px" multiple action="/" :on-change='onChangeFile' :on-remove="onRemoveFile"
            :auto-upload="false" :file-list=fileList>
            <el-button size="medium" type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="已上传附件" v-if="editForm.attachment && editForm.attachment.length > 0">
          <div style="width: 500px">
            <p v-for="v in editForm.attachment" :key="v.path" class="flex-space-between">
              <span class="shou xialine overhide_ mr16"
                @click="uploadFiles(v.file_path,v.file_name)">{{v.file_name}}</span>
              <i class="el-icon-close f-14" @click="delFiles(v)"></i>
            </p>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="flex-justify-bcenter">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit" :loading='btnLoading'>确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="editFormVisible2" width="650px" @click="editFormVisible2 = false" @close='dialogClose2'
      :close-on-click-modal='false' :close-on-press-escape='false'>
      <h2 slot="title" class="tx-c">上传验收报告</h2>
      <el-form autocomplete="off" label-width="120px" class="form_flex">
        <el-form-item label="验收报告">
          <el-upload style="width: 485px" multiple action="/" :on-change='onChangeFile' :on-remove="onRemoveFile"
            :auto-upload="false" :file-list=fileList>
            <el-button size="medium" type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="已上传报告" v-if="acceptObj.accept_file && acceptObj.accept_file.length > 0">
          <div style="width: 480px">
            <p v-for="v in acceptObj.accept_file" :key="v.path" class="flex-space-between">
              <span class="shou xialine overhide_ mr16"
                @click="uploadFiles(v.file_path,v.file_name)">{{v.file_name}}</span>
              <i class="el-icon-close f-14" @click="delFiles2(v)"></i>
            </p>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="flex-justify-bcenter">
        <el-button @click="editFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="yanShouSubmit" :loading='btnLoading'>确 定</el-button>
      </div>
    </el-dialog>
    <!-- 审核 -->
    <examine ref="examine" @submit='examineSubmit' :item='examine_item' />

    <gjdetails :info='details' ref="detail" />
  </div>
</template>

<script>
  import {
    ApiInternationalcontracts,
    ApiInternationalcontractsAdd,
    ApiInternationalcontractsPut,
    ApiInternationalcontractsDel,
    ApiInternationalcontractsCheck,
    ApiupLoadFiles,
    ApiInternationalcontractsAccept
  } from '@/api'
  import {
    reviewStatus,
    leaderType,
    leaderTypeObj
  } from "@/assets/js"
  import {debounce,adminShow,objToStr} from "@/utils/index";
  import {headerList,editForm} from '../js/international'
  import gjdetails from "../components/gjdetails.vue"
  import multipleSearch from "@/components/multipleSearch.vue"
  export default {
    name: 'project_international',
    components: {
      gjdetails,multipleSearch
    },
    computed: {
      editHeaderList() {
        let list = headerList.filter(item => item.prop !== 'review_status')
        return list.sort((a, b) => b.required - a.required)
      }
    },
    data() {
      return {
        objToStr,
        ApiInternationalcontracts,
        adminShow: adminShow(),
        reviewStatus,
        leaderType,

        tableData: [],
        editFormVisible: false,
        editForm, //修改或者查看详情

        pageparm: {
          page: 1,
          perPage: 20,
          total: null,
          sort_str: null,
          sort_order: 'desc',
        },
        tableLoading: false,

        btnLoading: false,

        headerList,
        rules: ['name', 'leader_id', 'leader_type', 'departments_id', 'contract_amount', 'manage_amount'],
        unitList: ["contract_amount", "manage_amount"],
        departmentsId: null,
        examine_id: null, //审核id
        examine_item: {
          view: false
        },

        middleList: [],
        personList: [],
        middleInfoList:[],
        dialogTitle: '',

        pickerOptions: {
          start_time: {},
          end_time: {},
        },
        details: {},
        editFormVisible2: false,
        fileList: [],
        acceptObj: {
          accept_file: [],
          yanShou_id: null,
        }
      }
    },
    activated() {
      this.getList()
    },
    methods: {
      unitShow(prop) {
        return this.unitList.includes(prop)
      },
      yanShou(item) {
        this.acceptObj.yanShou_id = item.id
        this.acceptObj.accept_file = [...item.accept_file]
        this.editFormVisible2 = true
      },
      yanShouSubmit() {
        const options = this.acceptObj
        if (this.fileList.length === 0 && options.accept_file.length === 0) {
          this.$message({
            type: 'error',
            message: '请上传验收附件'
          });
          return
        }
        this.btnLoading = true
        const formData = new FormData()
        this.fileList.forEach(item => {
          formData.append('files[]', item.raw)
        })
        if (options.accept_file && options.accept_file.length > 0) {
          options.accept_file.forEach(item => {
            formData.append('file_name[]', item.file_name)
            formData.append('file_path[]', item.path)
          })
        } else {
          formData.append('file_name[]', [])
          formData.append('file_path[]', [])
        }
        ApiInternationalcontractsAccept(formData, options.yanShou_id, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(res => {
          this.getList()
          this.$message({
            type: 'success',
            message: '验收报告上传成功'
          });
          this.editFormVisible2 = false
        }).finally(() => {
          this.btnLoading = false
        })
      },
      uploadFiles: debounce(function (url, name) {
        ApiupLoadFiles(url).then(res => {
          let a = document.createElement("a")
          a.href = URL.createObjectURL(res)
          a.download = name
          a.click()
          URL.revokeObjectURL(a.href)
        })
      }, 500, true),
      delFiles(v) {
        this.editForm.attachment = this.editForm.attachment.filter(item => item.id !== v.id)
      },
      delFiles2(v) {
        this.acceptObj.accept_file = this.acceptObj.accept_file.filter(item => item.id !== v.id)
      },
      onChangeFile(file, fileList) {
        this.fileList.push(file)
      },
      onRemoveFile(file, fileList) {
        this.fileList = fileList
      },
      dialogClose2() {
        this.fileList = []
      },
      viewDetails(val, ) {
        this.details = val
        this.$refs.detail.showInfo = true
      },
      goUserInfo(value) {
        sessionStorage.setItem('internationalName', value.name)
        this.$router.push('/project/international_members?id=' + value.id)
      },
      dataFn(data, tableHeade) {
        let tabStr = ''
        data.forEach((item, index) => {
          let tabRowStr = "";
          tabStr += `<tr>`;
          for (let i = 0; i < tableHeade.length; i++) {
            const key = tableHeade[i]
            if (key === 'departments_id') {
              tabRowStr += `<td>${item.department?item.department.name:''}</td>`;
            } else if (key === 'review_status') {
              tabRowStr += `<td>${item.status}${item.review_comment ? (':' + item.review_comment): ''}</td>`;
            } else if (key === 'complete_id') {
              tabRowStr += `<td>${objToStr(item.complete_name)}</td>`;
            } else if (key === 'leader_id') {
              tabRowStr += `<td>${item.leader_info?item.leader_info.name:'' }</td>`;
            } else if (key === 'leader_type') {
              tabRowStr += `<td>${leaderTypeObj[item.leader_type] || ''}</td>`;
            } else {
              tabRowStr += `<td>${item[key] || ''}</td>`;
            }
          }
          tabStr += tabRowStr;
          tabStr += "</tr>";
        });
        return tabStr
      },
      changeDate(t) {
        this.pickerOptions = {
          start_time: {
            disabledDate: (time) => {
              if (this.editForm.end_time) {
                return (time.getTime() >= new Date(this.editForm.end_time).getTime());
              }
              // else{
              //   return time.getTime() < (Date.now() - 86400000)
              // }
            }
          },
          end_time: {
            disabledDate: (time) => {
              if (this.editForm.start_time) { // 开始日期
                return (time.getTime() < new Date(this.editForm.start_time).getTime() - 86400000);
              }
              // else{
              //   return time.getTime() < Date.now() - 86400000
              // }
            }
          },
        }
      },
      //审核
      examineSubmit(options) {
        const loading = this.$loading({
          lock: true,
          text: '加载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        options.id = this.examine_id
        ApiInternationalcontractsCheck(options, options.id).then(res => {
          this.getList()
        }).catch(() => {
          this.$message.error('服务器错误，请重新提交');
        }).finally(() => {
          loading.close()
        })
      },
      examine_btns(item, i) {
        this.examine_id = item.id
        if (i > 1) {
          this.examine_item.review_status = item.review_status
          this.examine_item.review_comment = item.review_comment
          this.examine_item.view = true
        } else {
          this.examine_item.view = false
        }
        this.$refs.examine.examineShow = true

      },
      echo(i, arr) {
        let label
        for (const item of arr) {
          if (item.value === i) {
            label = item.label
            break;
          }
        }
        return label
      },
      tableSortChange(column) {
        if (column.order === "descending") {
          this.pageparm.sort_str = column.prop;
          this.pageparm.sort_order = "desc";
        } else if (column.order === "ascending") {
          this.pageparm.sort_str = column.prop;
          this.pageparm.sort_order = "asc";
        } else {
          this.pageparm.sort_str = null;
          this.pageparm.sort_order = null;
        }
        this.getList()
      },
      //搜索
      clearSearch() {
        this.$refs.search_e.clear()
        if (this.adminShow) this.$refs.search_d.clear()
      },
      searchChane(i, val) {
        this.pageparm[val] = i
        this.pageparm.page = 1
        this.getList()
      },
      //分页
      callFather(pageparm) {
        this.pageparm.page = pageparm.page
        this.pageparm.perPage = pageparm.perPage
        this.getList()
      },
      getList() {
        this.tableLoading = true
        ApiInternationalcontracts(this.pageparm).then(({
          data,
          page
        }) => {
          this.tableData = data || []
          this.pageparm.total = page.total
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      },
      handle(index, value, i) {
        for (const key in this.editForm) {
          this.editForm[key] = value[key]
        }
        this.editFormVisible = true
        this.dialogTitle = '新增国际合作'
        if (i == 2) {
          this.editForm.attachment = value.attachment ? [...value.attachment] : []
          this.dialogTitle = '编辑国际合作'
          this.$nextTick(() => {
            this.$refs.departmentSearch[0].departments_id = value.departments_id
            if (value.leader_info) this.middleList = [{
              employees_id: value.leader_id,
              employee: {
                name: value.leader_info.name
              }
            }]
            if (Array.isArray(value.complete_id) && value.complete_id.length > 0) {
              const arr = [],arr2 = [];
              for (const key in value.complete_name) {
                arr.push({
                  employees_id: Number(key),
                  employee:{
                    name:value.complete_name[key]
                  }
                })
                arr2.push(Number(key))
              }
              this.middleInfoList = arr
              this.personList = arr2
            }
          })
        } else {
          if (!this.adminShow) {
            this.editForm.departments_id = this.$store.state.userInfo.department_id
            this.$nextTick(() => {
              this.$refs.departmentSearch[0].departments_id = this.editForm.departments_id
            })
          }
        }
        this.changeDate()
      },
      departmentsChange(id) {
        this.editForm.departments_id = id
      },
      nameChange(id) {
        this.editForm.leader_id = id
      },
      completionChange(id) {
        this.editForm.complete_id = id
      },
      dialogClose() {
        this.$refs.departmentSearch[0].clear()
        this.$refs.e_Search[0].clear()
        this.$refs.e2_Search[0].clear()
        this.fileList = []
      },
      deleteUser(index, value) {
        this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const loading = this.$loading({
            lock: true,
            text: '加载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          ApiInternationalcontractsDel(value.id).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList()
          }).finally(() => {
            loading.close()
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      submit: debounce(function () { //提交  修改或新增
        const options = {
          ...this.editForm
        }
        for (const key of this.rules) {
          if (!options[key] && options[key] !== 0) {
            this.$message({
              type: 'error',
              message: '必填信息请填写完整！'
            });
            return
          }
        }
        this.btnLoading = true
        if (!options.manage_amount) options.manage_amount = 0
        const formData = new FormData()
        for (const i in options) {
          if (i !== 'attachment') {
            if (options[i] === null || options[i] === undefined) options[i] = ""
            if(i === 'complete_id'){  
              if(Array.isArray(options.complete_id) && options.complete_id.length > 0){
                options.complete_id.forEach(ele=>{
                  formData.append('complete_id[]', ele)
                })
              }else{
                formData.append('complete_id[]', [])
              }
            }else{
              formData.append(i, options[i])
            }
          }
        }
        if (this.fileList.length > 0) {
          this.fileList.forEach(item => {
            formData.append('files[]', item.raw)
          })
        }
        if (options.id) { //有ID就是修改
          if (options.attachment && options.attachment.length > 0) {
            options.attachment.forEach(item => {
              formData.append('file_name[]', item.file_name)
              formData.append('file_path[]', item.path)
            })
          } else {
            formData.append('file_name[]', [])
            formData.append('file_path[]', [])
          }
          ApiInternationalcontractsPut(formData, options.id, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }).then(res => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
            this.editFormVisible = false
            this.getList()
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '修改失败!'
            });
          }).finally(() => {
            this.btnLoading = false
          });
        } else {
          ApiInternationalcontractsAdd(formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }).then(res => {
            this.$message({
              type: 'success',
              message: '添加成功!'
            });
            this.editFormVisible = false
            this.getList()
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '添加失败!'
            });
          }).finally(() => {
            this.btnLoading = false
          });
        }
      }, 800, true)
    },

  }
</script>
<style lang='less' scoped>
</style>